<?php


namespace App\Models;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class News extends Model
{
    use HasDateTimeFormatter;
    protected $table = 'news';

    protected $softDeleteField = 'is_delete';

    protected $casts = [
        'is_delete' => 'integer'
    ];

    protected static function booted()
    {
        static::addGlobalScope('not_deleted', function (Builder $builder) {
            $builder->where('is_delete', 0);
        });
    }

    public function delete()
    {
        $this->is_delete = 1;
        return $this->save();
    }

    public function trashed()
    {
        return $this->is_delete === 1;
    }


    public function getContentAttribute($value)
    {
        if (empty($value)) {
            return $value;
        }

        $value = $this->addDomainToImages($value,env('IMAGE_URL'),env('IMAGE_URL_NEW'));


        return $value;
    }

    public function addDomainToImages($html, $domain, $domain2) {
        $domain = rtrim($domain, '/');
        $domain2 = rtrim($domain2, '/');

        $pattern = '/<img\s+(?:[^>]*?\s+)?src="([^"]*)"/i';

        return preg_replace_callback($pattern, function ($matches) use ($domain, $domain2) {
            $src = $matches[1];

            if (preg_match('/^https?:\/\//', $src)) {
                return $matches[0];
            }

            $selectedDomain = str_contains($src, '/new_cms_img/') ? $domain2 : $domain;

            if (str_starts_with($src, '/uppic')) {
                $newSrc = $selectedDomain . $src;
            } elseif (str_starts_with($src, '/storage')) {
                $newSrc = $selectedDomain . substr($src, 8);
            } else {
                $uppicPos = strpos($src, '/uppic');
                $newSrc = $uppicPos !== false
                    ? $selectedDomain . substr($src, $uppicPos)
                    : $selectedDomain . $src;
            }

            return preg_replace('/src="[^"]*"/i', 'src="' . $newSrc . '"', $matches[0]);
        }, $html);
    }
}
